{% extends "base.html" %}

{% block title %}数据管理{% endblock %}

{% block styles %}
    <style>
        .thumbnail {
            cursor: pointer;
            margin: 5px;
            height: 150px;
            object-fit: cover;
            width: 100%;
            border-radius: 5px;
        }
        
        .directory-card {
            margin-bottom: 2rem;
        }
        
        .selected-directory {
            background-color: #f0f0f0;
        }
        
        .img-container {
            position: relative;
            margin: 10px;
        }
        
        .img-delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 2;
            background-color: rgba(255, 0, 0, 0.9);
            color: white;
            border: none;
            padding: 6px 10px;
            font-size: 13px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .img-delete-btn:hover {
            background-color: rgba(255, 0, 0, 1);
            transform: scale(1.05);
        }
        
        /* Pagination fixes */
        .pagination-container {
            width: 100%;
            max-width: 100%;
            margin-top: 20px;
            text-align: center;
        }
        
        .pagination {
            display: inline-flex;
            flex-wrap: nowrap;
            margin: 0 auto;
            padding: 0;
        }
        
        .page-item.ellipsis {
            pointer-events: none;
            padding: 0.375rem 0.75rem;
        }
    </style>
{% endblock %}

{% block content %}

    <div class="container mt-4">
        <h3 class="mb-4">照片管理</h3>
        
        <div class="row">
            <div class="col-md-3">
                <h5>照片目录</h5>
                <div id="directory-list" class="list-group">
                    <!-- 目录列表将通过JavaScript动态加载 -->
                </div>
                <button id="refreshBtn" class="btn btn-primary mt-3 w-100">
                    刷新目录
                </button>

            </div>
            <div class="col-md-9">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 id="currentDirectory">当前目录：全部图片</h5>
                    <div>
              
                        <button id="oneClickUploadBtn" class="btn btn-info me-2">
                            <i class="bi bi-upload me-1"></i>一键上传
                        </button>

                        {% if session.role == 'super_user' %}
                        <button id="cropAndUploadBtn" class="btn btn-primary me-2">
                        <i class="bi bi-lightning-charge-fill me-1"></i>裁剪&分类 
                        </button>
                        <button id="uploadSelectedBtn" class="btn btn-success me-2">
                        上传目录 <i class="fa fa-cloud-upload" aria-hidden="true"></i>
                        </button>
                        {% endif %}
        
                        <button id="deleteSelectedBtn" class="btn btn-danger me-2">
                            删除目录
                        </button>
                        <button id="clearAllBtn" class="btn btn-danger">
                            清空所有
                        </button>
                    </div>
                </div>
                <div id="imageGrid" class="row g-3">
                    <!-- 缩略图将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <!-- Cropping Progress Modal -->
    <div class="modal fade" id="croppingProgressModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">正在处理图片...</h5>
                </div>
                <div class="modal-body text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">正在对图片进行裁剪处理，请稍候...</p>
                    <div id="croppingProgress" class="mt-3">
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
                        </div>
                        <small class="text-muted mt-2" id="croppingStatus"></small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Cropping Result Modal -->
    <div class="modal fade" id="croppingResultModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">裁剪结果</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="croppingResultBody">
                    <!-- Results will be inserted here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal for full size image view -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="imageModalLabel">图片预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <div id="imageFilename" class="mb-2 fw-bold"></div>
                    <img id="fullSizeImage" src="" class="img-fluid" alt="Full size image">
                </div>
            </div>
        </div>
    </div>

    <!-- Upload Progress Modal -->
    <div class="modal fade" id="uploadProgressModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">正在上传目录...</h5>
                </div>
                <div class="modal-body text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">正在上传目录及其子目录中的图片到FTP服务器，请稍候...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Upload Result Modal -->
    <div class="modal fade" id="uploadResultModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">上传结果</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="uploadResultBody">
                    <!-- Results will be inserted here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    <script>
        let currentDirectory = '';
        let selectedDirectory = '';

        // 获取目录列表
        function loadDirectories() {
            fetch('/api/photos/directories')
                .then(response => response.json())
                .then(data => {
                    const directoryList = document.getElementById('directory-list');
                    directoryList.innerHTML = '';

                    if (data.directories.length === 0) {
                        directoryList.innerHTML = '<p class="text-muted m-2">暂无目录</p>';
                        return;
                    }

                    data.directories.forEach(directory => {
                        const button = document.createElement('button');
                        button.className = 'list-group-item list-group-item-action directory-item';
                        if (directory === selectedDirectory) {
                            button.classList.add('active');
                        }
                        button.textContent = directory;
                        button.addEventListener('click', () => selectDirectory(directory));
                        directoryList.appendChild(button);
                    });
                })
                .catch(error => console.error('Error:', error));
        }

        // 选择目录
        function selectDirectory(directory) {
            selectedDirectory = directory;
            currentDirectory = directory;
            document.getElementById('currentDirectory').textContent = `当前目录：${directory}`;
            loadImages();
            loadDirectories(); // 重新加载目录以更新选中状态
        }

        // 加载图片
        function loadImages(page = 1) {
            const endpoint = currentDirectory ? `/api/photos/images?directory=${encodeURIComponent(currentDirectory)}&page=${page}&page_size=8` : `/api/photos/images?page=${page}&page_size=8`;
            fetch(endpoint)
                .then(response => response.json())
                .then(data => {
                    const imageGrid = document.getElementById('imageGrid');
                    imageGrid.innerHTML = '';
                    let pagination = document.getElementById('pagination');
                    if (!pagination) {
                        pagination = document.createElement('div');
                        pagination.id = 'pagination';
                        imageGrid.parentNode.appendChild(pagination);
                    }
                    pagination.innerHTML = '';
                    if (!data || !data.images || data.images.length === 0) {
                        imageGrid.innerHTML = '<p class="text-muted m-2">该目录下暂无图片</p>';
                        return;
                    }
                    const allImages = data.images;
                    const totalPages = Math.ceil(data.count / data.page_size);
                    let currentPage = data.page;
                    // 显示当前页的图片
                    for (let i = 0; i < allImages.length; i++) {
                        const image = allImages[i];
                        const col = document.createElement('div');
                        col.className = 'col-md-2-4 col-sm-3 col-4';
                        col.innerHTML = `
                            <div class="card img-container">
                                <img src="${image.thumbnailUrl || '#'}" class="card-img-top thumbnail" alt="${image.filename || 'Image'}" loading="lazy"
                                     onclick="viewImage('${image.fullUrl || '#'}', '${image.filename ? image.filename.replace(/'/g, "\\'") : ''}')">
                                <div class="card-body p-2">
                                    <p class="card-text text-truncate mb-1" title="${image.filename || ''}">${image.filename || 'Unknown'}</p>
                                    <small class="text-muted">
                                        ${image.size ? `${(image.size / 1024).toFixed(1)} KB` : '未知大小'}
                                    </small>
                                    <button class="btn btn-sm btn-danger img-delete-btn" 
                                            onclick="deleteImage(event, '${currentDirectory}', '${image.filename || ''}')">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                        imageGrid.appendChild(col);
                    }
                    // 更新分页控件
                    updatePagination(currentPage, totalPages);
                    function updatePagination(page, totalPages) {
                        pagination.innerHTML = '';
                        if (totalPages <= 1) return;
                        const nav = document.createElement('nav');
                        nav.className = 'pagination-container';
                        const ul = document.createElement('ul');
                        ul.className = 'pagination justify-content-center';
                        
                        // 上一页按钮
                        const prevLi = document.createElement('li');
                        prevLi.className = 'page-item' + (page === 1 ? ' disabled' : '');
                        prevLi.innerHTML = '<a class="page-link" href="#">上一页</a>';
                        prevLi.addEventListener('click', (e) => {
                            e.preventDefault();
                            if (page > 1) {
                                loadImages(page - 1);
                            }
                        });
                        ul.appendChild(prevLi);
                        
                        // 显示逻辑：最多显示7个页码按钮（包括省略号）
                        const maxVisiblePages = 5;
                        let startPage = Math.max(1, page - 2);
                        let endPage = Math.min(totalPages, page + 2);
                        
                        // 调整显示范围确保显示maxVisiblePages个页码
                        if (page <= 3) {
                            endPage = Math.min(maxVisiblePages, totalPages);
                        } else if (page >= totalPages - 2) {
                            startPage = Math.max(1, totalPages - maxVisiblePages + 1);
                        }
                        
                        // 第一页
                        if (startPage > 1) {
                            const firstLi = document.createElement('li');
                            firstLi.className = 'page-item';
                            firstLi.innerHTML = '<a class="page-link" href="#">1</a>';
                            firstLi.addEventListener('click', (e) => {
                                e.preventDefault();
                                loadImages(1);
                            });
                            ul.appendChild(firstLi);
                            
                            if (startPage > 2) {
                                const ellipsisLi = document.createElement('li');
                                ellipsisLi.className = 'page-item ellipsis';
                                ellipsisLi.innerHTML = '<span class="page-link">...</span>';
                                ul.appendChild(ellipsisLi);
                            }
                        }
                        
                        // 中间页码
                        for (let i = startPage; i <= endPage; i++) {
                            const li = document.createElement('li');
                            li.className = 'page-item' + (i === page ? ' active' : '');
                            li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                            li.addEventListener('click', (e) => {
                                e.preventDefault();
                                loadImages(i);
                            });
                            ul.appendChild(li);
                        }
                        
                        // 最后一页
                        if (endPage < totalPages) {
                            if (endPage < totalPages - 1) {
                                const ellipsisLi = document.createElement('li');
                                ellipsisLi.className = 'page-item ellipsis';
                                ellipsisLi.innerHTML = '<span class="page-link">...</span>';
                                ul.appendChild(ellipsisLi);
                            }
                            
                            const lastLi = document.createElement('li');
                            lastLi.className = 'page-item';
                            lastLi.innerHTML = `<a class="page-link" href="#">${totalPages}</a>`;
                            lastLi.addEventListener('click', (e) => {
                                e.preventDefault();
                                loadImages(totalPages);
                            });
                            ul.appendChild(lastLi);
                        }
                        
                        // 下一页按钮
                        const nextLi = document.createElement('li');
                        nextLi.className = 'page-item' + (page === totalPages ? ' disabled' : '');
                        nextLi.innerHTML = '<a class="page-link" href="#">下一页</a>';
                        nextLi.addEventListener('click', (e) => {
                            e.preventDefault();
                            if (page < totalPages) {
                                loadImages(page + 1);
                            }
                        });
                        ul.appendChild(nextLi);
                        
                        nav.appendChild(ul);
                        pagination.appendChild(nav);
                        const pageInfo = document.createElement('div');
                        pageInfo.className = 'text-center mt-3';
                        pageInfo.textContent = `第 ${page} 页（共 ${totalPages} 页） - 共 ${data.count} 张图片`;
                        pagination.appendChild(pageInfo);
                    }
                })
                .catch(error => {
                    console.error('Error fetching images:', error);
                    document.getElementById('imageGrid').innerHTML = 
                        '<p class="text-danger m-2">加载图片时发生错误</p>';
                });
        }

        // 查看原图
        function viewImage(fullUrl, filename) {
            const modal = new bootstrap.Modal(document.getElementById('imageModal'));
            document.getElementById('fullSizeImage').src = fullUrl;
            document.getElementById('imageFilename').textContent = filename || '';
            modal.show();
        }

        // 上传选中目录(包含子目录)
        function uploadSelectedDirectory() {
            if (!selectedDirectory) {
                alert('请先选择一个目录');
                return;
            }
            
            if (confirm(`确定要上传目录 "${selectedDirectory}" 及其所有子目录下的图片到FTP服务器吗？`)) {
                const loadingModal = new bootstrap.Modal(document.getElementById('uploadProgressModal'));
                loadingModal.show();
                
                fetch('/api/photos/upload', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ directory: selectedDirectory })
                })
                .then(response => response.json())
                .then(data => {
                    // 显示上传结果详情
                    const resultModal = new bootstrap.Modal(document.getElementById('uploadResultModal'));
                    const resultBody = document.getElementById('uploadResultBody');
                    
                    // 构建结果HTML
                    let html = `<h5>上传结果: ${data.message}</h5>`;
                    html += `<p>总文件数: ${data.uploaded_files.length}</p>`;
                    
                    // 按目录分组统计
                    const dirStats = {};
                    data.uploaded_files.forEach(file => {
                        const dir = file.directory || '根目录';
                        if (!dirStats[dir]) {
                            dirStats[dir] = { success: 0, failed: 0 };
                        }
                        if (file.status === 'success') {
                            dirStats[dir].success++;
                        } else {
                            dirStats[dir].failed++;
                        }
                    });
                    
                    // 添加目录统计
                    // html += '<div class="mt-3"><h6>目录统计:</h6><ul class="list-group">';
                    // for (const [dir, stats] of Object.entries(dirStats)) {
                    //     const successClass = stats.failed > 0 ? 'text-warning' : 'text-success';
                    //     html += `
                    //         <li class="list-group-item d-flex justify-content-between align-items-center">
                    //             ${dir || '根目录'}
                    //             <span class="badge ${successClass}">
                    //                 ${stats.success}成功 ${stats.failed > 0 ? stats.failed + '失败' : ''}
                    //             </span>
                    //         </li>`;
                    // }
                    // html += '</ul></div>';
                    
                    // // 添加失败详情(如果有)
                    // const failedFiles = data.uploaded_files.filter(f => f.status === 'failed');
                    // if (failedFiles.length > 0) {
                    //     html += '<div class="mt-3"><h6>失败文件:</h6><ul class="list-group">';
                    //     failedFiles.forEach(file => {
                    //         html += `
                    //             <li class="list-group-item">
                    //                 <div>${file.directory ? file.directory + '/' : ''}${file.file}</div>
                    //                 <small class="text-danger">${file.error}</small>
                    //             </li>`;
                    //     });
                    //     html += '</ul></div>';
                    // }
                    
                    resultBody.innerHTML = html;
                    loadingModal.hide();
                    resultModal.show();
                    
                    // 刷新图片列表
                    loadImages();
                })
                .catch(error => {
                    console.error('Error:', error);
                    loadingModal.hide();
                    alert('上传过程中发生错误: ' + error.message);
                });
            }
        }

        // 删除选中目录
        function deleteSelectedDirectory() {
            if (!selectedDirectory) {
                alert('请先选择一个目录');
                return;
            }
            
            if (confirm(`确定要删除目录 "${selectedDirectory}" 及其所有内容吗？此操作不可恢复！`)) {
                fetch('/api/photos/delete_directory', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ directory: selectedDirectory })
                })
                .then(response => response.json())
                .then(data => {
                    alert('删除成功');
                    if (data.success) {
                        selectedDirectory = '';
                        currentDirectory = '';
                        document.getElementById('currentDirectory').textContent = '当前目录：全部图片';
                        loadDirectories();
                        loadImages();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除过程中发生错误');
                });
            }
        }

        // 删除单个图片

        function deleteImage(event, directory, filename) {
            event.stopPropagation(); // 阻止点击事件冒泡到父元素
            
            // 添加调试日志
            console.log('Deleting file:', { directory, filename });

            if (confirm(`确定要删除图片 \"${filename}\" 吗？此操作不可恢复！`)) {
                fetch('/api/photos/delete_image', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        directory: directory,
                        filename: filename
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    alert(data.message || '删除成功');
                    if (data.success) {
                        loadImages();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert(`删除过程中发生错误: ${error.message}`);
                });
            }
        }
     

        // 清空所有文件
        function clearAllPhotos() {
            if (confirm('确定要清除所有图片吗？此操作不可恢复！')) {
                fetch('/api/photos/clear_all', {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    alert('已清空所有图片');
                    if (data.success) {
                        selectedDirectory = '';
                        currentDirectory = '';
                        document.getElementById('currentDirectory').textContent = '当前目录：全部图片';
                        loadDirectories();
                        loadImages();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('清空过程中发生错误');
                });
            }
        }

        // 一键裁剪功能
        function cropImages() {
            if (!selectedDirectory) {
                alert('请先选择一个目录');
                return;
            }

            if (confirm(`确定要对目录 "${selectedDirectory}" 中的图片进行裁剪处理吗？`)) {
                const loadingModal = new bootstrap.Modal(document.getElementById('croppingProgressModal'));
                loadingModal.show();

                fetch('/api/photos/crop', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ directory: selectedDirectory })
                })
                .then(response => response.json())
                .then(data => {
                    // 先关闭加载弹窗
                    loadingModal.hide();
                    
                    // 显示裁剪结果详情
                    const resultModal = new bootstrap.Modal(document.getElementById('croppingResultModal'));
                    const resultBody = document.getElementById('croppingResultBody');
                    
                    // 构建结果HTML
                    let html = `<h5>裁剪结果: ${data.message}</h5>`;
                    html += `<p>总文件数: ${data.processed_files.length}</p>`;
                    
                    // 处理结果统计
                    const stats = {
                        success: data.processed_files.filter(f => f.status === 'success').length,
                        skipped: data.processed_files.filter(f => f.status === 'skipped').length,
                        failed: data.processed_files.filter(f => f.status === 'failed').length
                    };
                    
                    // 添加统计信息
                    html += `
                        <div class="alert ${stats.failed > 0 ? 'alert-warning' : 'alert-success'} mt-3">
                            <ul class="mb-0">
                                <li>成功裁剪: ${stats.success} 个文件</li>
                                <li>跳过处理: ${stats.skipped} 个文件</li>
                                <li>处理失败: ${stats.failed} 个文件</li>
                            </ul>
                        </div>
                    `;
                    
                    // 添加失败详情(如果有)
                    const failedFiles = data.processed_files.filter(f => f.status === 'failed');
                    if (failedFiles.length > 0) {
                        html += '<div class="mt-3"><h6>失败文件:</h6><ul class="list-group">';
                        failedFiles.forEach(file => {
                            html += `
                                <li class="list-group-item">
                                    <div>${file.file}</div>
                                    <small class="text-danger">${file.error}</small>
                                </li>`;
                        });
                        html += '</ul></div>';
                    }
                    
                    resultBody.innerHTML = html;
                    resultModal.show();
                    
                    // 刷新图片列表
                    loadImages();
                })
                .catch(error => {
                    console.error('Error:', error);
                    // 确保加载弹窗关闭
                    try {
                        loadingModal.hide();
                    } catch (e) {
                        console.error('Error hiding loading modal:', e);
                    }
                    alert('裁剪过程中发生错误: ' + error.message);
                });
            }
        }

        // 一键上传功能（裁剪+上传）
        function oneClickUpload() {
            if (!selectedDirectory) {
                alert('请先选择一个目录');
                return;
            }

            if (confirm(`确定要对目录 "${selectedDirectory}" 执行一键上传操作吗？(包含裁剪和上传)`)) {
                const loadingModal = new bootstrap.Modal(document.getElementById('croppingProgressModal'));
                loadingModal.show();

                fetch('/api/photos/crop', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ directory: selectedDirectory })
                })
                .then(response => response.json())
                .then(data => {
                    loadingModal.hide();
                    
                    if (data.success) {
                        // 自动上传生成的pic目录
                        const picDirectory = 'pic'; // 假设裁剪后生成pic目录
                        selectedDirectory = picDirectory;
                        
                        const uploadModal = new bootstrap.Modal(document.getElementById('uploadProgressModal'));
                        uploadModal.show();
                        
                        fetch('/api/photos/upload', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ directory: picDirectory })
                        })
                        .then(response => response.json())
                        .then(uploadData => {
                            uploadModal.hide();
                            alert(`一键上传完成: ${uploadData.message}`);
                            loadImages();
                        })
                        .catch(uploadError => {
                            uploadModal.hide();
                            alert('上传过程中发生错误: ' + uploadError.message);
                        });
                    } else {
                        alert('裁剪失败: ' + data.message);
                    }
                })
                .catch(error => {
                    loadingModal.hide();
                    alert('裁剪过程中发生错误: ' + error.message);
                });
            }
        }

        // 页面初始化
        function init() {
            loadDirectories();
            loadImages();
            
        // 安全绑定按钮事件
        const bindButton = (id, handler) => {
            const btn = document.getElementById(id);
            if (btn) btn.addEventListener('click', handler);
        };
        
        bindButton('cropAndUploadBtn', cropImages);
        bindButton('oneClickUploadBtn', oneClickUpload);
        bindButton('uploadSelectedBtn', uploadSelectedDirectory);
        bindButton('deleteSelectedBtn', deleteSelectedDirectory);
        bindButton('clearAllBtn', clearAllPhotos);
        bindButton('refreshBtn', () => {
                selectedDirectory = '';
                currentDirectory = '';
                document.getElementById('currentDirectory').textContent = '当前目录：全部图片';
                loadDirectories();
                loadImages();
            });
        }

        // 初始化加载
        window.addEventListener('DOMContentLoaded', init);

        document.getElementById('goto-videos').onclick = function() {
      window.location.href = '/videos';
    };
    </script>
{% endblock %}
